<?php
/**
 * Created by PhpStorm.
 * User: guokunsheng
 * Date: 2020/10/12
 * Time: 17:49
 */

namespace app\astrologer\controller;

use app\common\cachemodel\AppConfig;
use app\common\cachemodel\ZlcrAppeal;
use app\common\cachemodel\ZlcrAstr;
use app\common\cachemodel\ZlcrAstrNotAnswerQuestion;
use app\common\cachemodel\ZlcrAstrQuestionNote;
use app\common\cachemodel\ZlcrContentCheck;
use app\common\cachemodel\ZlcrCustomReportGoods;
use app\common\cachemodel\ZlcrCustomReportQuestion;
use app\common\cachemodel\ZlcrCustomReportQuestionComment;
use app\common\cachemodel\ZlcrCustomReportQuestionInfo;
use app\common\lib\PushQueue;
use app\common\lib\Util;
use \Exception;
use think\Db;
use think\Env;
use think\Log;

/**
 * 占星师订单任务相关
 * Class Task
 * @support v1.0.0
 * @package app\astrologer\controller
 */
class Task extends AstrAuth
{
    protected $firstCompleteAnswerTime;// 第一次接单后回答完成时长
    protected $completeAnswerTime;// 接单后回答完成时长

    public function _initialize()
    {
        parent::_initialize();
        $this->firstCompleteAnswerTime = Env::get('queue.custom_report_answer4_delay');
        $this->completeAnswerTime = Env::get('queue.custom_report_answer6_delay');
    }

    /**
     * 获取可领取任务数量
     * @throws Exception
     */
    public function getTaskNum()
    {
        $notAnswerQids = (new ZlcrAstrNotAnswerQuestion())->getNotAnswerQids($this->astrInfo['id']);

        $questionNUm = (new ZlcrCustomReportQuestion())->getCustomReportQueueNum($notAnswerQids);

        return show(config('code.success'), '请求成功', [
            'question_num' => $questionNUm,
        ]);
    }

    /**
     * 获取占星师任务列表
     * @method GET
     * @throws Exception
     */
    public function list()
    {
        $question = trim(input('question/s', ''));
        // h5
        $param['start_time'] = $this->request->param('start_time/s', 0);
        $param['end_time'] = $this->request->param('end_time/s', 0);
        // pc
        $rangeTime = input('range_time/a', []);
        $qtype = input('qtype/a', []);
        $param['status'] = $this->request->only(['status']);
        $page = input('page/d', 1);
        $limit = input('limit/d', 10);
        $sort = input('sort/s', 'astr_receiving_time DESC');// 默认接单时间倒序
        $isIndex = input('index/d', 0);

        $astrQuestionNoteModel = new ZlcrAstrQuestionNote();

        if ($isIndex)
        {
            $data = [
                'total' => 1,
                'current_page' => 1,
                'per_page' => 10,
                'last_page' => 1,
                'data' => [],
            ];

            $astrModel = new ZlcrAstr();
            $customReportQuestionModel = new ZlcrCustomReportQuestion();

            // 获取用户正在进行中的任务
            $qids = $astrModel->getUnderwayTask($this->astrInfo['id']);
            $questionTaskList = [];
            foreach ($qids as $qid)
            {
                $questionInfo = $customReportQuestionModel->getInfoById($qid);
                $noteData = $astrQuestionNoteModel->getQuestionNote($this->astrInfo['id'], $qid);
                $questionTaskList[] = [
                    'qid' => $qid,
                    // 'order_id' => $questionInfo['order_num'],// 订单id
                    'question' => $questionInfo['question_name'],// 用户问题
                    'astr_receiving_time' => (int)$questionInfo['astr_receiving_time'],// 接单时间
                    'status' => (int)$questionInfo['status'],// 问题状态
                    'qtype' => (int)$questionInfo['qtype'],// 问题类型 1=>固定问题,2=>自定义问题
                    'is_merge' => (int)$questionInfo['is_merge'],// 是否为合盘问题 0=>否,1=>是
                    'is_back' => 0,// 是否退款
                    'check_time1' => (int)$questionInfo['check_time1'],// 问题审核时间
                    'check_time2' => (int)$questionInfo['check_time2'],// 回答后审核时间
                    'answer_time' => (int)$questionInfo['answer_time'],// 占星师解答时间
                    // 'tid' => (int)$questionInfo['id'],// 用户评价标签id
                    'earnings' => Util::getAstrCustomReportEarnings($questionInfo['order_num'], $this->astrInfo['proportion']),
                    // 'rate' => 4,// 用户评价星级🌟
                    // 'fadeback' => '算的好准，希望能帮助更多的人！',// 用户评价反馈文字
                    'note' => $noteData ? $noteData['note'] : '',// 占星师对该问题的备注
                ];
            }

            $data['data'] = $questionTaskList;
        } else
        {
            $map = [
                'q.astr_id' => (int)$this->astrInfo['id'],
            ];

            if (!empty($rangeTime))
            {
                $start_time = strtotime($rangeTime[0]);
                $end_time = strtotime($rangeTime[1]);
                $map['astr_receiving_time'] = ['between', [$start_time, $end_time]];
            } else if (($param['start_time'] && $param['end_time']))
            {
                $start_time = strtotime($param['start_time']);
                $end_time = strtotime($param['end_time']);
                if ($end_time < $start_time)
                {
                    return show(0, '开始时间不能大于结束时间！');
                } else
                {
                    $map['astr_receiving_time'] = ['between', [$start_time, $end_time]];
                }

            } else if ($param['start_time'])
            {
                $start_time = strtotime($param['start_time']);
                $map['astr_receiving_time'] = ['>=', $start_time];
            } else if ($param['end_time'])
            {
                $map['astr_receiving_time'] = ['<', strtotime($param['start_time'])];
            }

            if (!empty($qtype))
            {
                foreach ($qtype as $k => $v)
                {
                    $qtype[$k] = (int)$v;
                }
                $map['q.qtype'] = ['in', $qtype];
            }

            if ($param['status'])
            {
                if (is_array($param['status']['status']))
                {
                    foreach ($param['status']['status'] as $k => $v)
                    {
                        $param['status']['status'][$k] = (int)$v;
                    }
                    if ($param['status']['status'][0] === 5)
                    {// 如果是已完成，那么把评价待审核和已评价也加上
                        $param['status']['status'][] = 6;
                        $param['status']['status'][] = 7;
                    }
                    $map['q.status'] = ['in', $param['status']['status']];
                } else
                {
                    $status = [];
                    foreach ($param['status'] as $k => $v)
                    {
                        $status[] = (int)$v;
                    }
                    if ($status[0] === 5)
                    {// 如果是已完成，那么把评价待审核和已评价也加上
                        $status[] = 6;
                        $status[] = 7;
                    }
                    $map['q.status'] = ['in', $status];
                }

            }

//            if (!empty($status))
//            {
//                if (is_array($status))
//                {
//                    foreach ($status as $k => $v)
//                    {
//                        $status[$k] = (int)$v;
//                    }
//                    $map['status'] = ['in', $status];
//                } else
//                {
//                    $status_in = [];
//                    foreach ($status as $k => $v)
//                    {
//                        $status_in[] = (int)$v;
//                    }
//                    $map['status'] = ['in', $status_in];
//                }
//
//
//            }
            // 按问题名称搜索
            if ($question !== '')
            {
                $map['q.question_name'] = ['like', '%' . $question . '%'];
            }

            $data = Db::table('wechat_backup_07_18_14_43_00.zlcr_custom_report_question')->alias('q')
                ->join('wechat_backup_07_18_14_43_00.zlcr_astr_account_record a', 'a.qid=q.id')
                ->field('q.id qid,q.answer_time,q.astr_receiving_time,q.check_time1,q.check_time2,q.is_back,q.is_merge,q.qtype,q.question_name question,q.status,q.tid,a.amount earnings,a.type zlcr_astr_account_record_type')
                ->where($map)
                ->order($sort)
                ->paginate($limit, false, ['page' => $page])
                ->toArray();

            $qids = array_column($data['data'], 'qid');
//            $commentList = (new ZlcrCustomReportQuestionComment())->alias('c')->join('wechat_backup_07_18_14_43_00.zlcr_tag t', 'c.tid=t.id')->whereIn('c.qid', $qids)->column('c.level,c.status,c.comment,c.appeal_status,c.create_time,t.tag_name tname', 'c.qid');
            $commentList = (new ZlcrCustomReportQuestionComment())->alias('c')->join('wechat_backup_07_18_14_43_00.zlcr_tag t', 'c.tid=t.id')->whereIn('c.qid', $qids)->column('c.level,c.tid,t.tag_name tname,t.score', 'c.qid');
            foreach ($data['data'] as $key => $dataItem)
            {
                $noteData = $astrQuestionNoteModel->getQuestionNote($this->astrInfo['id'], $dataItem['qid']);
                $data['data'][$key]['note'] = $noteData ? $noteData['note'] : '';

                if ((int)$dataItem['zlcr_astr_account_record_type'] === 3)
                {
                    $data['data'][$key]['earnings'] = 0;
                    $data['data'][$key]['status'] = 17;
                }
                unset($data['data'][$key]['zlcr_astr_account_record_type']);

//                $data['data'][$key]['comment_data'] = null;
//                if ((int)$dataItem['status'] === 7 && isset($commentList[$dataItem['qid']]))
//                {
//                    if ($commentList[$dataItem['qid']]['appeal_status'])
//                    {
//                        $level = 3;
//                        $comment = '平淡无味';
//                    } else
//                    {
//                        $level = (int)$commentList[$dataItem['qid']]['level'];
//                        $comment = (int)$commentList[$dataItem['qid']]['status'] === 3 ? '' : $commentList[$dataItem['qid']]['comment'];
//                    }
                if ((int)$dataItem['status'] === 7 && isset($commentList[$dataItem['qid']]))
                {
                    $data['data'][$key]['rate'] = (int)$commentList[$dataItem['qid']]['level']; // 标签星级
                    $data['data'][$key]['tname'] = $commentList[$dataItem['qid']]['tname']; // 标签名字
                    $data['data'][$key]['grade_change'] = $commentList[$dataItem['qid']]['score']; // 变动能力值
                } else
                {
                    $data['data'][$key]['rate'] = 0;
                    $data['data'][$key]['tname'] = '';
                }

//                    $data['data'][$key]['comment_data'] = [
//                        'level' => $level,
//                        'comment' => $comment,
//                        'create_time' => (int)$commentList[$dataItem['qid']]['create_time'],
//                        'tname' => $commentList[$dataItem['qid']]['tname'],
//                    ];
//                }
            }
        }


        return show(config('code.success'), '请求成功', $data);
    }

    /**
     * 接单
     * @method GET
     * @throws Exception
     */
    public function get()
    {
        $astrModel = new ZlcrAstr();
        $customReportQuestionModel = new ZlcrCustomReportQuestion();
        if ((int)$this->astrInfo['check_status'] !== 40)
        {
            return show(config('code.error'), '账号状态异常，接单失败');
        }

        $authStatus = $this->astrInfo['auth_status'];
        if ($authStatus['custom_report'] !== 1)
        {
            return show(config('code.error'), '账号状态异常，接单失败');
        }

        if ((int)$this->astrInfo['status'] === 2 || $this->astrInfo['pause_time'] - $this->request->time() > 0)
        {
            return show(config('code.error'), '账号已被冻结，接单失败');
        }
        // 判断是否有待回答的问题
        $qids = $astrModel->getUnderwayTask($this->astrInfo['id']);
        if ($qids)
        {   // 如果有未完成的问题
            $qid = current($qids);
            $questionInfo = $customReportQuestionModel->getInfoById($qid);

            $noteData = (new ZlcrAstrQuestionNote())->getQuestionNote($this->astrInfo['id'], $qid);
            $data = [
                'qid' => $qid,
                'order_id' => $questionInfo['order_num'],// 订单id
                'question' => $questionInfo['question_name'],// 用户问题
                'astr_receiving_time' => (int)$questionInfo['astr_receiving_time'],// 接单时间
                'status' => (int)$questionInfo['status'],// 问题状态 3=>等待回答
                'qtype' => (int)$questionInfo['qtype'],// 问题类型 1=>固定问题,2=>自定义问题
                'is_merge' => (int)$questionInfo['is_merge'],// 是否为合盘问题 0=>否,1=>是
                'earnings' => Util::getAstrCustomReportEarnings($questionInfo['order_num'], $this->astrInfo['proportion']), // 预计收益
                // 'is_back' => $questionInfo['is_back'],// 是否退款
                'check_time1' => (int)$questionInfo['check_time1'],// 问题审核时间
//            'check_time2' => $questionInfo['check_time2'],// 回答后审核时间
//            'answer_time' => $questionInfo['answer_time'],// 占星师解答时间
//            'tid' => $questionInfo['check_time1'],// 用户评价标签id
//            'rate' => $questionInfo['check_time1'],// 用户评价星级🌟
//            'fadeback' => '',// 用户评价反馈文字
                'note' => $noteData ? $noteData['note'] : '',// 占星师对该问题的备注
            ];

            return show(config('code.success'), '请求成功', $data);
        }

        if ($this->isConsultAstro && $this->consultAccountInfo['team_id'])
        {   // 特邀咨询师 没有接单资格
            return show(config('code.error'), '特邀咨询师暂不支持接收定制报告任务');
        }

        $notAnswerQids = (new ZlcrAstrNotAnswerQuestion())->getNotAnswerQids($this->astrInfo['id']);

        $qid = $customReportQuestionModel->CustomReportQueuePop($notAnswerQids);

        if (!$qid)
        {
            return show(config('code.error'), '暂无合适的问题；请稍后再试～');
        }
        $qid = (string)$qid;

        $questionInfo = $customReportQuestionModel->getInfoById($qid);

        if ((int)$questionInfo['status'] !== 2)
        {   // 不是待接单状态
            Log::write('占星师接单问题状态异常！' . \GuzzleHttp\json_encode($questionInfo, JSON_UNESCAPED_UNICODE), 'error', true);
            return show(config('code.error'), '服务异常！请稍后再试～');
        }

        $updateData = [
            'status' => 3, // 问题待解答
            'astr_receiving_time' => $this->request->time(), // 接单时间
            'astr_id' => $this->astrInfo['id'], // 占星师ID
        ];

        $customReportQuestionModel->updateData($questionInfo['uid'], $qid, $updateData); // 更新问题信息

        $astrModel->underwayTaskAdd($this->astrInfo['id'], $qid); // 添加进行中的任务

        $data = [
            'qid' => $qid,
            'order_id' => $questionInfo['order_num'],// 订单id
            'question' => $questionInfo['question_name'],// 用户问题
            'astr_receiving_time' => $this->request->time(),// 接单时间
            'status' => $updateData['status'],// 问题状态 3=>等待回答
            'qtype' => (int)$questionInfo['qtype'],// 问题类型 1=>固定问题,2=>自定义问题
            'is_merge' => (int)$questionInfo['is_merge'],// 是否为合盘问题 0=>否,1=>是
            'earnings' => Util::getAstrCustomReportEarnings($questionInfo['order_num'], $this->astrInfo['proportion']), // 预计收益
            // 'is_back' => $questionInfo['is_back'],// 是否退款
            'check_time1' => (int)$questionInfo['check_time1'],// 问题审核时间
//            'check_time2' => $questionInfo['check_time2'],// 回答后审核时间
//            'answer_time' => $questionInfo['answer_time'],// 占星师解答时间
//            'tid' => $questionInfo['check_time1'],// 用户评价标签id
//            'rate' => $questionInfo['check_time1'],// 用户评价星级🌟
//            'fadeback' => '',// 用户评价反馈文字
            'note' => '',// 占星师对该问题的备注
        ];

        // 添加6小时后任务是否完成检查队列 参数 qid 和 adstr_id
        $jobData = [
            'id' => $qid,
            'astr_id' => $this->astrInfo['id'],
            'push_switch' => 1,
        ];
        (new PushQueue())->customReportInvalid(['pay_time' => $questionInfo['pay_time'], 'astr_receiving_time' => $this->request->time(), 'qtype' => $data['qtype']], 2, $jobData);

        // 发送钉钉通知
        Util::sendZlcrMsg(3, [
            '占星师名字：' . $this->astrInfo['nickname'],
            '问题：' . $questionInfo['question_name'],
        ], $this->headers['app-type']);
        return show(config('code.success'), '请求成功', $data);
    }

    /**
     * 弃答
     * @method POST
     * @throws Exception
     */
    public function discard()
    {
        $qid = input('qid/s', '');// 问题id

        if (!$qid)
        {
            return show(config('code.error'), '请求失败');
        }
        // 检测今日可弃答次数是否大于等于2
        $notAnswerQids = (new ZlcrAstrNotAnswerQuestion())->getNotAnswerQids($this->astrInfo['id']);
        if (count($notAnswerQids) >= 3)
        {
            return show(config('code.error'), '今日已无弃答次数！');
        }
        $customReportQuestionModel = new ZlcrCustomReportQuestion();
        $questionInfo = $customReportQuestionModel->getInfoById($qid, ['status', 'astr_id', 'astr_receiving_time', 'uid']);
        if (!$questionInfo || (int)$questionInfo['astr_id'] !== $this->astrInfo['id'])
        {
            return show(config('code.error'), '服务异常！问题不存在～');
        }

        if ($this->request->time() - $questionInfo['astr_receiving_time'] >= 300)
        {   //
            return show(config('code.error'), '距离接单超过5分钟；不可弃答～');
        }

        if ((int)$questionInfo['status'] !== 3)
        { // 待回答状态
            return show(config('code.error'), '问题状态异常；弃答失败～');
        }

        // todo 判断问题如果被弃答三次 则问题失效
        try
        {
            Db::startTrans();
            // 开始弃答
            $customReportQuestionModel->updateData($questionInfo['uid'], $qid, [
                'status' => 2, // 问题待接单
                'astr_receiving_time' => 0,
                'astr_id' => 0,
            ]);

            (new ZlcrAstrNotAnswerQuestion())->notAnswerQuestionAdd([
                'astr_id' => $this->astrInfo['id'],
                'qid' => $qid,
                'type' => 1,
                'remark' => '',
            ]); // 添加弃答记录
            Db::commit();
        }
        catch (Exception $e)
        {
            Db::rollback();
            Log::write('占星师后台：问题弃答失败：' . $e->getMessage() . ';错误文件' . $e->getFile() . ';错误行数:' . $e->getLine(), 'error', true);
            return show(config('code.error'), '弃答失败；服务异常！请稍后再试～');
        }
        $astrModel = new ZlcrAstr();
        $astrModel->underwayTaskDel($this->astrInfo['id'], [$qid]); // 待解答问题删除
        // 将问题抛回问题池
        $customReportQuestionModel->CustomReportQueueAdd($qid, 2);

        return show(config('code.success'), '请求成功');
    }

    /**
     * 回答问题
     * @method POST
     * @throws Exception
     */
    public function answer()
    {
        $qid = input('qid/s', '');// 问题id
        $content = input('content/s', '', 'trim');// 回答内容

        if (!$qid || $content === '')
        {
            return show(config('code.error'), '请求失败');
        }

        if (mb_strlen($content) < 800)
        {
            return show(config('code.error'), '字数不能少于800！');
        }
        // 判断问题是否是当前占星师 并且 问题待回答状态
        $questionInfo = (new ZlcrCustomReportQuestion())->getInfoById($qid, ['astr_id', 'status', 'question_name', 'uid']);
        if (!$questionInfo || (int)$questionInfo['astr_id'] !== $this->astrInfo['id'])
        {
            return show(config('code.error'), '服务异常！问题不存在～');
        }

        if (!in_array($questionInfo['status'], [3, 13], false))
        {
            if ((int)$questionInfo['status'] === 4)
            {
                return show(config('code.error'), '问题已回答！');
            }

            return show(config('code.error'), '问题状态异常；请稍后再试～');
        }

        // 问题解答
        (new ZlcrCustomReportQuestionInfo())->updateData(['answer_content' => $content], $qid);
        $updateData = [
            'status' => 4, // 待审核
            'answer_time' => $this->request->time(),
        ];
        (new ZlcrCustomReportQuestion())->updateData($questionInfo['uid'], $qid, $updateData);

        // 添加审核数据
        (new ZlcrContentCheck())->saveData([
            'type' => 2,
            'status' => 1,
            'qid' => $qid,
            'create_time' => $this->request->time(),
        ]);

        // 发送钉钉通知
        Util::sendZlcrMsg(4, [
            '提问内容：' . $questionInfo['question_name'],
            '解答的占星师昵称：' . $this->astrInfo['nickname'],
        ], $this->headers['app-type']);
        return show(config('code.success'), '解答成功；答案审核中～');
    }

    /**
     * 获取问题状态：
     * 1.已接单15分钟内的被取消的订单，在占星师后台阻塞提示（可通用阻塞）
     * 2.回复审核未通过，占星师后台，刷新状态
     * 3.回复审核通过，占星师后台，刷新状态
     * @return \think\response\Json
     * @throws Exception
     */
    public function getTaskIsCancle()
    {
        $qid = input('qid/s', '');

        if (!$qid)
        {
            return show(config('code.error'), '请求失败');
        }

        $questionInfo = (new ZlcrCustomReportQuestion())->getInfoById($qid, ['status', 'astr_id']);

        if (!$questionInfo || (int)$questionInfo['astr_id'] !== $this->astrInfo['id'])
        {
            return show(config('code.error'), '服务异常！问题不存在～');
        }

        // 未被接单正在队列中取消订单原渠道全额退款
        // 如已被接单进行中15分钟内取消订单退款90%
        // 如超过15分钟不支持退款

        $data = [
            'show_dialog' => 0, // 0：不显示dialog；1：显示不可以关闭的dialog；2：显示可以关闭的dialog
            'dialog_title' => '',// dialog的标题（只有show_dialog为1的时候才返回内容，否则为空）
            'dialog_msg' => '',// dialog的内容描述（只有show_dialog为1的时候才返回内容，否则为空）
            'dialog_btn' => '',
            'target' => '',
            'link' => '',
        ];

        if ((int)$questionInfo['status'] === 15)
//        if (true) // test
        { // 15=>用户取消订单（占星师未接单；占星师已接单；）
            $data['show_dialog'] = 1;
            $data['dialog_title'] = '订单已强制取消';
            $data['dialog_msg'] = '非常抱歉，因用户取消订单，此订单已失效，此订单金额的10%作为您的补偿金，请您到历史收益中查看';
            $data['dialog_btn'] = '历史收益';
            $data['target'] = 'local';
            $data['link'] = '/earnings/list';
            $data['qid'] = $qid;
        } else
        {
            $data['status'] = (int)$questionInfo['status'];
        }
        return show(config('code.success'), '请求成功', $data);

    }

    /**
     * 获取问题详情
     *  回答问题时
     *  问题审核未通过进行修改时
     * @method GET
     * @throws Exception
     */
    public function details()
    {
        $qid = input('qid/s', '');

        if (!$qid)
        {
            return show(config('code.error'), '请求失败');
        }

        $questionInfo = (new ZlcrCustomReportQuestion())->getInfoById($qid, ['question_name', 'qtype', 'astr_id', 'status', 'is_merge', 'check_time1', 'astr_receiving_time', 'pay_time', 'check_time2', 'answer_time', 'gid']);

        if (!$questionInfo || (int)$questionInfo['astr_id'] !== $this->astrInfo['id'])
        {
            return show(config('code.error'), '服务异常！问题不存在～');
        }

        $noteData = (new ZlcrAstrQuestionNote())->getQuestionNote($this->astrInfo['id'], $qid);

        $questionInfo['status'] = (int)$questionInfo['status'];
        $answerContent = '';
        if (in_array($questionInfo['status'], [4, 13, 5, 6, 7, 12], true))
        { // 问题可能已回答
            $questionContentInfo = (new ZlcrCustomReportQuestionInfo())->getInfoById($qid, ['answer_content']);
            $answerContent = $questionContentInfo ? $questionContentInfo['answer_content'] ?? '' : '';
        }
        $reason = '';
        if ($questionInfo['status'] === 13)
        {
            $conetntCheckInfo = (new ZlcrContentCheck())->getContentCheckInfo($qid, 2, ['status', 'desc', 'check_time']);
            if ($conetntCheckInfo && (int)$conetntCheckInfo['status'] === 3)
            {   // 审核不通过
                $reason = $conetntCheckInfo['desc'] ?? '';
            }
        }

        // 判断是否是固定问题，如果是固定问题，那么查询 回答的模板 和 示例图片
        $temp = [
            'name' => '',
            'example_name' => '',
            'example_url' => '',
        ];// 固定问题模板

        // 问题类型 1=>固定问题,2=>自定义问题
        $questionGoods = (new ZlcrCustomReportGoods())->getInfoById($questionInfo['gid'], ['required_temp', 'option_temp', 'example_url']);
        // 问题模板
        if ($questionGoods && ($questionGoods['required_temp'] || $questionGoods['option_temp'] || $questionGoods['example_url']))
        {
            $temp = $questionGoods;
            $temp['name'] = '推荐内容模版';
            $temp['example_name'] = '报告示例';
            $temp['example_url'] = $questionGoods['example_url'];
        } else
        {// 打印错误日志，告诉后台人员添加模板
            Log::write('占星师后台接单异常：固定问题，缺少模板/示例图片；固定问题id：' . $questionInfo['gid'], 'error', true);
        }

        $hasSupplementInfo = 0;
        try
        {
            $sex_des = '';// 盘主性别提示
            $recordeInfo = (new ZlcrCustomReportQuestionInfo())->getInfoById($qid, ['recode_info', 'supplement_info']);
            $hasSupplementInfo = $recordeInfo['supplement_info'] ? 1 : 0;
            $recode_info = $recordeInfo ? $recordeInfo['recode_info'] ?? '' : '';
            if ($recode_info)
            {
                $recodes = json_decode($recode_info, true);
                $recode1 = $recodes['recode1'];
                $recode2 = $recodes['recode2'];
                if ($recode1 && $recode2)
                {// 合盘
                    if (isset($recode1['type']) && isset($recode2['type']))
                    {
                        $sex_des = '盘主：' . '本命1' . ((int)$recode1['type'] === 1 ? '男' : '女') . '、本命2' . ((int)$recode2['type'] === 1 ? '男' : '女');
                    }
                } else if ($recode1 && isset($recode1['type']))
                {// 一个档案
                    $sex_des = '盘主：' . ((int)$recode1['type'] === 1 ? '男' : '女');
                }
            }
        }
        catch (Exception $e)
        {
            Log::write('盘主性别获取失败：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
        }

        // 问题等待回答
        $data = [
            'qid' => $qid,
            'question' => $questionInfo['question_name'],// 用户问题
            'content' => $answerContent,
            'status' => $questionInfo['status'],// 问题状态 3=>等待回答
            'qtype' => (int)$questionInfo['qtype'],// 问题类型 1=>固定问题,2=>自定义问题
            'is_merge' => (int)$questionInfo['is_merge'],// 是否为合盘问题 0=>否,1=>是
            'check_time1' => (int)$questionInfo['check_time1'],// 问题审核时间
            'check_time2' => (int)$questionInfo['check_time2'],// 回答后审核时间
            'answer_time' => (int)$questionInfo['answer_time'],// 占星师解答时间
            'note' => $noteData ? $noteData['note'] : '',// 占星师对该问题的备注
            'reason' => $reason, // 答案审核不通过原因
            'temp' => $temp, // 回复模版和示例图片
            'sex_des' => $sex_des, // 盘主描述
            'has_supplement_info' => $hasSupplementInfo, // 是否有补充问题 1有 0没有
        ];

        $expireTime = 0;
        $expireDesc = '';
        // 计算问题失效时间 问题状态  0=>待支付 1=>问题待审核 2=>问题待接单 3=>问题待解答 4=>解答待审核 5=>已完成待评价 6=>已评价待审核 7=>评价已审核完成 10=>问题审核未通过失效 11=>订单派发超时失效 12=>占星师超时未完成失效 13=>问题待解答（答案审核未通过）14=>占星师拒答三次或申诉通过失效 15=>用户取消订单，金额退回90% 16=>用户取消订单，金额全部退回
        if (in_array($questionInfo['status'], [3, 4, 13], false))
        {
            // 待回复或者待审核中
            if ($questionInfo['status'] == 3)
            {
                $time1 = $questionInfo['astr_receiving_time'] + $this->firstCompleteAnswerTime - time();
                $time2 = $questionInfo['pay_time'] + $this->completeAnswerTime - time();
                $expireTime = $time1 < $time2 ? $time1 : $time2; // 取最小时间
                $expireDesc = $time1 < $time2 ? '问题回复超时将会导致账号被冻结，该订单无收益，请您尽快回答！首次回答请在4小时内完成。' : '问题回复超时将会导致账号被冻结，该订单无收益，请您尽快回答！';
            } else
            {
                $expireTime = $questionInfo['pay_time'] + $this->completeAnswerTime - time();
                $expireDesc = $questionInfo['status'] == 4 ? '若超时仍未通过审核，则账号将被冻结。' : '问题回复超时将会导致账号被冻结，该订单无收益，请您尽快回答！';
            }
        }

        $data['expire_time'] = $expireTime;
        $data['expire_desc'] = $expireDesc;
//        // 回答审核未通过
//        $data = [
//            'qid' => $qid,
//            'question' => '我今年的爱情运势？',// 用户问题
//            'status' => 13,// 问题状态 3=>等待回答
//            'qtype' => 1,// 问题类型 1=>固定问题,2=>自定义问题
//            'is_merge' => 0,// 是否为合盘问题 0=>否,1=>是
//            'check_time1' => 0,// 问题审核时间
//            'check_time2' => 0,// 回答后审核时间
//            'answer_time' => 0,// 占星师解答时间
//            'note' => '',// 占星师对该问题的备注
//            'reason' => '检查到您的回答中涉嫌发布广告'
//        ];

        return show(config('code.success'), '请求成功', $data);
    }

    /**
     * 获取问题补充问题
     * @throws Exception
     */
    public function getSupplementInfo()
    {
        $qid = input('qid/s', '');

        $supplementInfo = (new ZlcrCustomReportQuestionInfo())->getInfoById($qid, ['supplement_info', 'abnormal_supplement_info']);

        if (isset($supplementInfo['supplement_info']) && $supplementInfo['supplement_info'])
        {
            $customReportInfoConfig = (new AppConfig())->configInfo('custom_report');

            if ($customReportInfoConfig['supplement_question'] == 3 && $supplementInfo['abnormal_supplement_info'])
            {
                $supplementInfo = \GuzzleHttp\json_decode($supplementInfo['abnormal_supplement_info']);
            } else
            {
                $supplementInfo = \GuzzleHttp\json_decode($supplementInfo['supplement_info']);
            }
        } else
        {
            $supplementInfo = [];
        }

        return show(config('code.success'), '请求成功', $supplementInfo);
    }

    /**
     * 获取问题失效时间
     * @param $payTime 下单时间
     * @param $astrReceivingTime 占星师接单时间
     * @param $hour int  失效时长
     * @return int
     */
    public function getCustomqueueExpireTime($payTime, $astrReceivingTime, int $hour, $status)
    {
        $time = $this->request->time();
        // 16:00 - 23:59获取第二天八点的时间戳
        // 00:00 - 7:59获取当天八点的时间戳
        $payTimeHour = date('G', $payTime);// 获取当前支付的小时
        $astrReceivingTimeHour = date('G', $astrReceivingTime);// 获取当前支付的小时
        $expireTime = false;
        if ($payTimeHour >= 16 || $payTimeHour < 8)
        {
            if ($astrReceivingTimeHour >= 16 && $astrReceivingTimeHour <= 23)
            {
                $toTime = strtotime(date('Y-m-d 08:00:00', strtotime('+1day', $astrReceivingTime)));// 获取第二天八点的时间戳
                $expireTime = $toTime - $time + ($hour * 3600);
            } elseif ($astrReceivingTimeHour >= 0 && $astrReceivingTimeHour <= 7)
            {
                $toTime = strtotime(date('Y-m-d 08:00:00', $astrReceivingTime));// 获取第二天八点的时间戳
                $expireTime = $toTime - $time + ($hour * 3600);
            }
        }

        if ($expireTime === false)
        {
            $expireTime = $astrReceivingTime + ($hour * 3600) - time();
        }

        return $expireTime >= 0 ? $expireTime : 0;
    }

    /**
     * 问题备注
     * @method POST
     */
    public function note()
    {
        $qid = input('qid/s', '');
        $note = input('note/s', '');

        if (!$qid || !$note)
        {
            return show(config('code.error'), '请求失败');
        }

        $res = (new ZlcrAstrQuestionNote())->saveData([
            'qid' => $qid,
            'astr_id' => $this->astrInfo['id'],
            'note' => $note,
            'time' => $this->request->time(),
        ]);

        if ($res)
        {
            return show(config('code.success'), '备注成功');
        }

        return show(config('code.error'), '服务异常！备注失败～');
    }

    /**
     * 问题或评论申诉
     * @method POST
     * @throws Exception
     */
    public function complain()
    {
        $qid = input('qid/s', '');// 问题ID
        $reason = input('reason/s', '');// 申诉理由
        $type = input('type/d', 1);// 申诉类型 1=>问题申诉，2=>评论申诉

        if (!$qid || !$reason || !in_array($type, [1, 2], true))
        {
            return show(config('code.error'), '请求失败');
        }

        $questionInfo = (new ZlcrCustomReportQuestion())->getInfoById($qid, ['astr_id', 'status', 'astr_receiving_time']);

        if (!$questionInfo || (int)$questionInfo['astr_id'] !== $this->astrInfo['id'])
        {
            return show(config('code.error'), '服务异常！问题不存在～');
        }

        if ($type === 1 && $this->request->time() - $questionInfo['astr_receiving_time'] >= 900)
        {
            return show(config('code.error'), '距离接单超过15分钟；不可弃答～');
        }
        $questionInfo['status'] = (int)$questionInfo['status'];
        if (($type === 1 && $questionInfo['status'] !== 3) || ($type === 2 && $questionInfo['status'] !== 7))
        { // 待回答状态
            return show(config('code.error'), '问题状态异常；申诉失败～');
        }

        $res = (new ZlcrAppeal())->saveData([
            'type' => $type,
            'qid' => $qid,
            'astr_id' => $this->astrInfo['id'],
            'reason' => $reason,
            'time' => $this->request->time(),
        ]);

        if ($res)
        {
            return show(config('code.success'), '申诉成功');
        }

        return show(config('code.error'), '服务异常！申诉失败～');
    }

    /**
     * 问题或评论取消申诉
     * @method POST
     * @throws Exception
     */
    public function cancelComplain()
    {
        $qid = input('qid/s', '');// 问题ID
        $type = input('type/d', 1);// 申诉类型 1=>问题申诉，2=>评论申诉

        if (!$qid || !in_array($type, [1, 2], true))
        {
            return show(config('code.error'), '请求失败');
        }

        $res = (new ZlcrAppeal())->cancelAppeal($this->astrInfo['id'], $qid, $type);

        if ($res)
        {
            return show(config('code.success'), '取消申诉成功');
        }

        return show(config('code.error'), '服务异常！取消申诉失败～');
    }
}
